package com.facebook.fresco.samples.showcase.imageformat;

import com.facebook.animated.giflite.GifDecoder;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.Animatable;
import com.facebook.drawee.drawable.ScaleTypeDrawable;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.view.ResUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.fresco.samples.showcase.ResourceTable;
import com.facebook.fresco.samples.showcase.ShowcaseApplication;
import com.facebook.fresco.samples.showcase.misc.ImageUriProvider;
import com.facebook.imagepipeline.common.ImageDecodeOptions;
import com.facebook.imagepipeline.common.ImageDecodeOptionsBuilder;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.AbsButton;
import ohos.agp.components.Button;
import ohos.agp.components.Switch;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.FrameAnimationElement;
import ohos.utils.net.Uri;
import pl.droidsonroids.gif.LibraryLoader;

public class ImageFormatGifAbility extends Ability {

    private Entry[] mSpinnerEntries;

    private Button mFpinnerSelectDecoder;
    private SimpleDraweeView mSimpleDraweeView;
    private GifDecoder mGifDecoder;
    private boolean mAutoPlayEnabled;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_layout_format_gif);
        LibraryLoader.initialize(getApplicationContext());

        mGifDecoder = new GifDecoder();
        mSpinnerEntries =
                new Entry[] {
                        new Entry(
                                ResourceTable.String_format_gif_label_small,
                                ShowcaseApplication.imageUriProvider.createGifUri(ImageUriProvider.ImageSize.S)),
                        new Entry(
                                ResourceTable.String_format_gif_label_medium,
                                ShowcaseApplication.imageUriProvider.createGifUri(ImageUriProvider.ImageSize.M)),
                        new Entry(
                                ResourceTable.String_format_gif_label_large,
                                ShowcaseApplication.imageUriProvider.createGifUri(ImageUriProvider.ImageSize.L)),
                };
        /*
        mFpinnerSelectDecoder = (Button) findComponentById(ResourceTable.Id_fpinner_select_decoder);
        mFpinnerSelectDecoder.setClickedListener(view -> {
        });
         */

        mSimpleDraweeView = (SimpleDraweeView) findComponentById(ResourceTable.Id_drawee_view);
        final Switch switchBackground = (Switch) findComponentById(ResourceTable.Id_switch_background);
        /*
        switchBackground.setCheckedStateChangedListener((absButton, isChecked) -> {
            mSimpleDraweeView
                    .getHierarchy()
                    .setBackgroundImage(isChecked ? new CheckerBoardDrawable(getResources()) : null);
        });

         */

        final Switch switchAutoPlay = (Switch) findComponentById(ResourceTable.Id_switch_autoplay);
        switchAutoPlay.setCheckedStateChangedListener((absButton, isChecked) -> {
            mAutoPlayEnabled = isChecked;
            refreshAnimation();
        });

        mAutoPlayEnabled = switchAutoPlay.isEnabled();
        /*
        final Switch switchAspect = findComponentById(ResourceTable.Id_switch_aspect_ratio);

        switchAspect.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        ViewGroup.LayoutParams layoutParams = mSimpleDraweeView.getLayoutParams();
                        layoutParams.height = layoutParams.width * (isChecked ? 2 : 1);
                        mSimpleDraweeView.setLayoutParams(layoutParams);
                    }
                });

         */
        refreshAnimation();

    }

    private void refreshAnimation() {
        final Entry spinnerEntry = mSpinnerEntries[0];
        setAnimationUri(spinnerEntry.uri);
    }

    private void setAnimationUri(Uri uri) {
        final PipelineDraweeControllerBuilder controllerBuilder =
                Fresco.newDraweeControllerBuilder()
                        .setAutoPlayAnimations(mAutoPlayEnabled)
                        .setOldController(mSimpleDraweeView.getController());
        final ImageDecodeOptionsBuilder optionsBuilder =
                ImageDecodeOptions.newBuilder().setMaxDimensionPx(4000);

        if (mGifDecoder != null) {
            optionsBuilder.setCustomImageDecoder(mGifDecoder);
        }

        controllerBuilder.setImageRequest(
                ImageRequestBuilder.newBuilderWithSource(uri)
                        .setImageDecodeOptions(optionsBuilder.build())
                        .build());
        if (!mAutoPlayEnabled) {
            controllerBuilder.setControllerListener(new ControllerListener<ImageInfo>() {
                @Override
                public void onSubmit(String id, Object callerContext) {}

                @Override
                public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                    if (animatable != null) {
                     //   mSimpleDraweeView.getHierarchy().setOverlayImage(getPlayOverlayDrawable());
                        mSimpleDraweeView.setClickedListener(v -> {
                            /*
                            if (animatable.start()) {
                                animatable.stop();
                                mSimpleDraweeView.getHierarchy().setOverlayImage(getPlayOverlayDrawable());
                            } else {

                            }
                             */
                            animatable.start();
                            mSimpleDraweeView.getHierarchy().setOverlayImage(null);
                        });
                    }
                }

                @Override
                public void onIntermediateImageSet(String id, ImageInfo imageInfo) {}
                @Override
                public void onIntermediateImageFailed(String id, Throwable throwable) {}
                @Override
                public void onFailure(String id, Throwable throwable) {}
                @Override
                public void onRelease(String id) {}
            });
        } else {
            mSimpleDraweeView.getHierarchy().setOverlayImage(null);
        }
        mSimpleDraweeView.setController(controllerBuilder.build());
    }

    public Element getPlayOverlayDrawable() {
        return new ScaleTypeDrawable(
                ResUtil.getDrawable(this,ResourceTable.Media_icon),
                ScalingUtils.ScaleType.CENTER);
    }


    private static class Entry {
        final int descriptionId;
        final Uri uri;

        private Entry(int descriptionId, Uri uri) {
            this.descriptionId = descriptionId;
            this.uri = uri;
        }
    }
}
